function plusReady() {
    PaintAdv();
    // 缓存是否有数据
    var cachecity = JSON.parse(plus.storage.getItem(storageManager.currentcity));
    if (cachecity) {
        // 定位当前城市，默认杭州
        $("#currentcityname").text(cachecity.name);
        loadDisCountList(cachecity.id, cachecity.lat, cachecity.lng);
    } else {
        // 启动定位获取坐标
        gpsPosition();
    }

    // 绑定页面事件
    bindEvent();
}

if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

function settingAppPlus() {
    // 已运行页
    console.log("统计：已运行界面" + plus.webview.all().length);

    // 隐藏滚动条
    plus.webview.currentWebview().setStyle({
        scrollIndicator: 'none'
    });
    // Android处理返回键
    plus.key.addEventListener('backbutton', function () {
        if (confirm('确认退出？')) {
            plus.runtime.quit();
        }
    }, false);
}

// 调用APIGPS定位
function gpsPosition() {
    plus.geolocation.getCurrentPosition(
        function (position) {
            //获取地理坐标信息
            var codns = position.coords;
            console.log("GPS:" + "X:" + codns.latitude + " Y:" + codns.longitude);
            getCurrentCity(codns.latitude, codns.longitude);
        },
        function (e) {
            console.log("获取位置信息失败：" + e.message);
            getCurrentCity(30.33933004639136, 120.1033046481549);
        });
}

// 根据坐标获取当前城市
function getCurrentCity(lat, lng) {
    console.log(configManager.RequstUrl + 'api/common/position?lat=' + lat + '&lng=' + lng);
    $.ajax({
        type: 'Get',
        url: configManager.RequstUrl + 'api/common/position?lat=' + lat + '&lng=' + lng
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }
        var currentcity = data.data;

        console.log("定位当前城市为：" + currentcity.name);
        // 定位当前城市，默认杭州
        $("#currentcityname").text(currentcity.name);

        // 定位成功加载当前城市产品
        loadDisCountList(currentcity.id, lat, lng);

        // 放入缓存
        var cityData = { "id": currentcity.id, "parent_id": currentcity.parent_id, "name": currentcity.name, "lat": lat, "lng": lng };
        plus.storage.setItem(storageManager.currentcity, JSON.stringify(cityData));

        try {
            // 通知商家页更新
            plus.webview.getWebviewById(pageName.merchant).evalJS("selectcity()");
        } catch (err) { }

    }).fail(function () {
        // 默认杭州
        var cityData = { "id": 383, "parent_id": 31, "name": "杭州", "lat": 30.33928387105413, "lng": 120.1032966187033 };
        plus.storage.setItem(storageManager.currentcity, JSON.stringify(cityData));

        try {
            // 通知商家页更新
            plus.webview.getWebviewById(pageName.merchant).evalJS("selectcity()");
        } catch (err) { }
    });
}

// 城市切换
function selectcity() {
    // 缓存是否有数据
    var cachecity = JSON.parse(plus.storage.getItem(storageManager.currentcity));
    if (cachecity) {
        console.log("切换城市：" + cachecity.name);
        $("#currentcityname").text(cachecity.name);
        // 重新加载商品
        loadDisCountList(cachecity.id, cachecity.lat, cachecity.lng);
    }
}

// 加载优惠商品列表
function loadDisCountList(cityid, lat, lng) {
    // 检查网络状况
    if (!checkNetworkHeath()) { return; }

    var params = [];
    // 用户是否登陆
    var currentUser = JSON.parse(plus.storage.getItem(storageManager.user));
    if (currentUser) {
        params.push("userid=" + currentUser.id);
        params.push("city=" + cityid);
    } else {
        params.push("city=" + cityid);
    }
    params.push("lat=" + lat);
    params.push("lng=" + lng);
    params.push("limit=" + 20);

    console.log("接口：" + configManager.RequstUrl + "api/common/index?" + params.join("&"));
    // 当前城市
    $.ajax({
        type: 'Get',
        url: configManager.RequstUrl + "api/common/index?" + params.join("&")
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }

        // 画优惠产品
        if (data.data.goods.list && data.data.goods.count > 0) {
            paintGoodsList(data.data.goods.list);
        }

        // 商品数据不够20条填充商家数据
        if (!(data.data.goods.list && data.data.goods.count > 20)) {
            if (data.data.store.list && data.data.store.count > 0) {
                // 画商家
                paintStoreList(data.data.store.list);
            }
        }

        try { myScroll.refresh(); } catch (err) { }
    });

}


// 画优惠商品列表
function paintGoodsList(goodslist) {
    var html = [];
    for (var i = 0; i < goodslist.length; i++) {
        var goods = goodslist[i];
        html.push("<div name='goodsItem' class='item-01-wrap' tip='" + goods.id + "'><ul class='item-01-block'>");
        html.push("<li class='img-part'> <img src='" + configManager.goodsImgurl.format(goods.pic, "184-220") + "'><b></b></li>");
        html.push("<li class='tips-part'><p><i class=\"dollar icon\"></i>消费" + goods.store.offline_pay_fee + "%</p><p><i class=\"bitcoin icon\"></i>金币" + goods.store.coin_pay_fee + "%</p></li>");

        var address = goods.store.store_address;
        if (goods.store.store_address.length > 18)
        { address = address.substr(0, 18) + '...'; }

        html.push("<li class='text-part'><h2>" + goods.title + "</h2><p>" + address + "</p><p><span style='color:#f30; font-size:1.4em;'>￥" + goods.price + "</span>&nbsp;&nbsp;<span style='color:#999;text-decoration:line-through;'>" + goods.market_price + "</span></p></li>");
        html.push("</ul></div>");
    }


    $("#discountgoodlist").html(html.join(""));
}

// 商家
function paintStoreList(storelist) {
    var html = [];
    for (var i = 0; i < storelist.length; i++) {
        var merchant = storelist[i];
        var store_pic = configManager.storeImgurl.format(merchant.store_pic, "150-120");
        var distancestr = '';
        if (merchant.store_distance) {
            distancestr = parseFloat(merchant.store_distance).toFixed(2) + "km";
        }

        html.push("<div class='item-02-wrap bottom-line' style='background:#fff; margin-top:2px' name='shopitem' tip='" + merchant.id + "'>");
        html.push("<ul class='item-01-block '>");
        html.push("<li class='img-part'> <img src= '" + store_pic + "' width='75' height='53'> </li>");
        html.push("<li class='text-part2'><p>");

        html.push("<span class='icon gold_icon'>奖</span>");
        if (merchant.is_noreserve > 0) {
            html.push("<span class='icon red_icon'>约</span>");
        }
        if (merchant.is_refund > 0) {
            html.push("<span class='icon green_icon'>退</span>");
        }
        if (merchant.is_groupbuy > 0) {
            html.push("<span class='icon orange_icon'>团</span>");
        }
        if (merchant.is_takeaway > 0) {
            html.push("<span class='icon blue_icon'>外</span>");
        }

        html.push(merchant.store_name + "</p><p>" + DrawScore(merchant.store_score) + " <span style='color:#777; font-size:0.9em'>(" + merchant.reviews + "评价)</span></p>");
        html.push("<p><span class='f-r'>" + distancestr + "</span>" + merchant.store_address + "</p></li>");
        html.push("</ul><div class='off-left-tips1'> </div>");
        html.push("</div>");
    }


    $("#discountgoodlist").html(html.join(""));
}

// 绑定事件
function bindEvent() {
    $("#menulist").find("a").on("click", function () {
        plus.webview.getWebviewById(pageName.main).evalJS("redirect('footermerchant')");
        var tip = $(this).attr("tip");
        // 通知商家列表页更新
        plus.webview.getWebviewById(pageName.merchant).evalJS("receiveHomeEvent('" + tip + "')");
    });

    // 优惠产品
    $("#discountgoodlist").on("click", " div[name=goodsItem]", function () {
        // 跳转订单详情
        clicked('../mine/goods/detail.html?goodsid=' + $(this).attr("tip"), false, false, "pop-in");
    });

    // 最近商家
    $("#discountgoodlist").on("click", "div[name=shopitem]", function () {
        // 跳转商家详情
        clicked("../merchant/detail.html?storeid=" + $(this).attr("tip"), false, false, "pop-in");
    });

}

var myScroll, pullDownEl, pullDownOffset, pullUpEl, pullUpOffset;
function loaded() {
    pullDownEl = document.getElementById('pullDown');
    pullDownOffset = pullDownEl.offsetHeight;
    pullUpEl = document.getElementById('pullUp');
    pullUpOffset = pullUpEl.offsetHeight;

    myScroll = new iScroll('wrapper', {
        useTransition: false,
        fadeScrollbar: true,
        fixedScrollbar: true,
        scrollbarClass: "myScrollbar",
        topOffset: pullDownOffset,
        hScroll: false,
        onBeforeScrollStart: function (e) {
            if (this.absDistY > (this.absDistX + 5)) {
                // user is scrolling the x axis, so prevent the browsers' native scrolling
                e.preventDefault();
            }
        },
        onRefresh: function () {
            if (pullDownEl.className.match('loading')) {
                pullDownEl.className = '';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉即可刷新';
            } else if (pullUpEl.className.match('loading')) {
                pullUpEl.className = '';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '';
            }
        },
        onScrollMove: function () {
            if (this.y > 5 && !pullDownEl.className.match('flip')) {
                pullDownEl.className = 'flip';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '松开刷新...';
                this.minScrollY = 0;
            } else if (this.y < 5 && pullDownEl.className.match('flip')) {
                pullDownEl.className = '';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉即可刷新...';
                this.minScrollY = -pullDownOffset;
            } else if (this.y < (this.maxScrollY - 5) && !pullUpEl.className.match('flip')) {
                pullUpEl.className = 'flip';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '释放刷新...';
                this.maxScrollY = this.maxScrollY;
            } else if (this.y > (this.maxScrollY + 5) && pullUpEl.className.match('flip')) {
                pullUpEl.className = '';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '加载中...';
                this.maxScrollY = pullUpOffset;
            }
        },
        onScrollEnd: function () {
            if (pullDownEl.className.match('flip')) {
                pullDownEl.className = 'loading';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '加载中...';
                pullDownAction();	// Execute custom function (ajax call?)
            } else if (pullUpEl.className.match('flip')) {
                pullUpEl.className = 'loading';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '加载中...';
                pullUpAction();	// Execute custom function (ajax call?)
            }
        }
    });

    setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
}

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);

// 下拉
function pullDownAction() {
    // 判断当前网络状况
    if (!checkNetworkHeath()) { try { myScroll.refresh(); } catch (err) { } return; }
    setTimeout(function () {
        var cachecity = JSON.parse(plus.storage.getItem(storageManager.currentcity));
        if (cachecity) {
            // 重新加载商品
            loadDisCountList(cachecity.id, cachecity.lat, cachecity.lng);
        }
    }, 1000);
}
// 上滑
function pullUpAction() {
    try { myScroll.refresh(); } catch (err) { }
}

function checkNetworkHeath() {
    // 判断当前网络状况
    var currentNetworkType = plus.networkinfo.getCurrentType();
    console.log("当前网络" + currentNetworkType);
    if (currentNetworkType && (plus.networkinfo.CONNECTION_UNKNOW == currentNetworkType || plus.networkinfo.CONNECTION_NONE == currentNetworkType)) {
        plus.nativeUI.alert("无网络连接！");
        return false;
    }

    return true;
}


function DrawScore(score) {
    var pic = '0';
    if (score > 1 && score < 2) {
        pic = '1';
    } else if (score > 2 && score < 3) {
        pic = '2';
    } else if (score == 3) {
        pic = '3';
    } else if (score > 3 && score < 4) {
        pic = '35';
    } else if (score == 4) {
        pic = '4';
    } else if (score > 4 && score < 5) {
        pic = '45';
    } else if (score == 5) {
        pic = '5';
    } else {
        pic = '0';
    }
    return '<img width="74" height="10" src="http://i3.dpfile.com/s/i/app/api/32_' + pic + 'star.png" />';
}

// 画广告位
function PaintAdv() {
    // 头部
    $.ajax({
        type: 'Get',
        url: configManager.RequstUrl + "api/ads/posi?mark=indextop"
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }
        if (!data.data.ads || data.data.ads.length <= 0) { return; }

        var html = [];
        html.push("<div class='mui-slider-group mui-slider-loop'>");

        for (var i = 0; i < data.data.ads.length; i++) {
            var adv = data.data.ads[i];
            var src = configManager.adsImgurl.format(adv.pic, "") + '640-220';
            if (i == 0) {
                html.push("<div name='advitem' class='mui-slider-item mui-slider-item-duplicate'><a tip='" + adv.url + "'><img src='" + src + "'></a></div>");
            }

            html.push("<div name='advitem' class='mui-slider-item'><a tip='" + adv.url + "'><img src='" + src + "'></a></div>");

            if (i == data.data.ads.length - 1) {
                html.push("<div name='advitem' class='mui-slider-item mui-slider-item-duplicate'><a tip='" + adv.url + "'><img src='" + src + "'></a></div></div>");
            }
        }

        html.push("<div class='mui-slider-indicator' style='text-align:right; right:8px;bottom:3px'>");
        for (var i = 0; i < data.data.ads.length; i++) {
            var indi = (i == 0) ? "<div class='mui-indicator mui-active'></div>" : "<div class='mui-indicator'></div>";
            html.push(indi);
        }
        html.push("</div>");
        $("#slider").html(html.join(""));

        // 点击广告
        $("div[name=advitem]").on("click", function () {
            var url = $(this).find('a').attr('tip');
            if (url && url != "") {
                clicked(url, false, false, 'pop-in');
            }
        });
        settingAdvScroll();
    });

    $.ajax({
        type: 'Get',
        url: configManager.RequstUrl + "api/ads/posi?mark=indexmiddle"
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }
        if (!data.data.ads || data.data.ads.length <= 0) { return; }
        var adv = data.data.ads[0];
        var src = configManager.adsImgurl.format(adv.pic, "") + '640-100';

        html = [];
        html.push("<div id='midadvitem' tip='" + adv.url + "'> ");
        html.push("<ul class='index-notice '><li> <img src='" + src + "' /></li></ul>");
        html.push("</div>");
        $("#advindexmiddle").html(html.join(""));
        $("#midadvitem").on("click", function () {
            var url = $(this).attr('tip');
            if (url && url != "") {
                clicked(url, false, false, 'pop-in');
            }
        });
    });
}


// 设置广告滚动
function settingAdvScroll() {
    mui.init({
        swipeBack: true //启用右滑关闭功能
    });
    var slider = mui("#slider");
    slider.slider({ interval: 3000 });
}

// 获取图片路径
function SetImageUrl(imglist, picid, httpImageUrl) {
    console.log(httpImageUrl);
    var filename = "_doc/image/news/" + "/ads1" + picid + ".png";
    // 判断本地是否存在该图片
    plus.io.resolveLocalFileSystemURL(filename, function (entry) {
        setImgSrc(imglist, filename);
    },
    function (e) {
        // 不存在下载图片到本地
        var dtask = plus.downloader.createDownload(httpImageUrl, { filename: filename }, function (d, status) {
            if (status == 200) {
                console.log("存在图片" + d.filename);
                setImgSrc(imglist, d.filename);
            } else { console.log("下载失败"); }
        });
        dtask.start();
    });
}

function setImgSrc(imglist, url) {
    for (var i = 0; i < imglist.length; i++) {
        url = "file://" + plus.io.convertLocalFileSystemURL(url);
        console.log(url);
        $(imglist[i]).attr("src", url);
    }
}